import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Comment } from './comment.entity';
import { Feed } from '../feeds/feed.entity';

@Injectable()
export class CommentsService {
  constructor(
    @InjectRepository(Comment)
    private commentRepository: Repository<Comment>,
    @InjectRepository(Feed)
    private feedRepository: Repository<Feed>,
  ) {}

  // 为动态添加评论
  async addComment(userId: number, postId: number, content: string): Promise<Comment> {
    // 首先检查动态是否存在
    const feed = await this.feedRepository.findOne({ where: { id: postId } });
    if (!feed) {
      throw new Error('动态不存在');
    }

    // 创建评论
    const comment = this.commentRepository.create({
      userId,
      postId,
      content,
    });

    return await this.commentRepository.save(comment);
  }

  // 获取动态的所有评论
  async getCommentsByPostId(postId: number): Promise<Comment[]> {
    return await this.commentRepository
      .createQueryBuilder('comment')
      .where('comment.post_id = :postId', { postId })
      .leftJoinAndSelect('comment.user', 'user')
      .orderBy('comment.createdAt', 'ASC')
      .getMany();
  }

  // 删除评论
  async deleteComment(userId: number, commentId: number): Promise<boolean> {
    const result = await this.commentRepository.delete({ id: commentId, userId });
    return (result.affected ?? 0) > 0;
  }
}